package com.winning.pmph.service;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.core.conditions.update.LambdaUpdateWrapper;
import com.baomidou.mybatisplus.core.toolkit.IdWorker;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.google.common.collect.Lists;
import com.twelvemonkeys.lang.StringUtil;
import com.winning.pmph.entity.*;
import com.winning.pmph.mapper.HistoryMapper;
import com.winning.pmph.mapper.KnowledgeMapper;
import com.winning.pmph.utils.*;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.collections.CollectionUtils;
import org.apache.commons.io.FileUtils;
import org.apache.commons.lang3.StringUtils;
import org.jetbrains.annotations.NotNull;
import org.jsoup.Jsoup;
import org.jsoup.nodes.Document;
import org.jsoup.nodes.Element;
import org.jsoup.parser.Parser;
import org.jsoup.select.Elements;
import org.springframework.stereotype.Component;
import org.springframework.transaction.annotation.Transactional;

import javax.annotation.Resource;
import java.io.BufferedInputStream;
import java.io.File;
import java.io.IOException;
import java.net.HttpURLConnection;
import java.net.URL;
import java.text.SimpleDateFormat;
import java.util.*;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
import java.util.stream.Collectors;

/**
 * @author wu_di@winning.com.cn
 * @date 2021/1/21
 */
@Slf4j
@Component
@Transactional
public class KnowledgeService extends ServiceImpl<KnowledgeMapper, Knowledge> {
    @Resource
    private KnowledgeLibService knowledgeLibService;
    @Resource
    private TagService tagService;
    @Resource
    private RuleItemService ruleItemService;
    @Resource
    private ReleasedKnowledgeService releasedKnowledgeService;
    @Resource
    private TempKnowledgeService tempKnowledgeService;
    @Resource
    private TempKnowledgeFieldService tempKnowledgeFieldService;
    @Resource
    private ReleasedKnowledgeFieldService releasedKnowledgeFieldService;
    @Resource
    private KnowledgeHistoryService knowledgeHistoryService;
    @Resource
    private TaskItemService taskItemService;
    @Resource
    private KnowledgeSyncStatusService knowledgeSyncStatusService;
    @Resource
    private HistoryMapper historyMapper;
    @Resource
    private ActivityItemService activityItemService;
    @Resource
    private KnowledgeLibFieldService knowledgeLibFieldService;
    /*@Resource
    private FileLibService fileLibService;*/

    public TempKnowledge createKnowledgeByLibId(String knowledgeLibId) {
        TempKnowledge knowledge = new TempKnowledge();
        knowledge.setKnowledgeLibId(knowledgeLibId);
        knowledge.setId(IdWorker.getIdStr());
        createAndSetKnowledgeFieldList(knowledge);
        return knowledge;
    }

    public void createAndSetKnowledgeFieldList(Knowledge knowledge) {
        List<KnowledgeLibField> knowledgeLibFieldList = knowledgeLibService.getKnowledgeLibFieldList(knowledge.getKnowledgeLibId());
        List<KnowledgeField> knowledgeFieldList = Lists.newArrayList();
        for (KnowledgeLibField knowledgeLibField : knowledgeLibFieldList) {
            KnowledgeField knowledgeField = createFieldByLibField(knowledgeLibField);
            knowledgeField.setKnowledgeId(knowledge.getId());
            knowledgeFieldList.add(knowledgeField);
        }
        // 第一个字段为名称;
        knowledgeFieldList.get(0).setProperty(knowledge.getName());
        knowledge.setKnowledgeFieldList(knowledgeFieldList);
    }

    @NotNull
    public KnowledgeField createFieldByLibField(KnowledgeLibField knowledgeLibField) {
        KnowledgeField knowledgeField = JSON.parseObject(JSON.toJSONString(knowledgeLibField), TempKnowledgeField.class);
        knowledgeField.setKnowledgeLibFieldId(knowledgeLibField.getId());
        knowledgeField.setId(IdWorker.getIdStr());
        if (Objects.equals(KnowledgeLibField.FIELD_KIND_RICHEDITOR, knowledgeField.getKind())) {
            knowledgeField.setSource(new JSONArray());
        }
        return knowledgeField;
    }

    private int countTheNumberOfWords(String knowledgeId) {
        List<TempKnowledgeField> tempKnowledgeFields = tempKnowledgeFieldService.lambdaQuery().eq(TempKnowledgeField::getKnowledgeId, knowledgeId).list();
        int words = 0;
        for (TempKnowledgeField tempKnowledgeField : tempKnowledgeFields) {
            int num = KnowledgeEditUtil.countWords(tempKnowledgeField);
            words += num;
        }
        return words;
    }

    /**
     * 保存知识
     * step:
     * 1: 记录history(操作历史)
     * 2: 保存任务项(统计字数, nameSuggestion)
     * 3: 保存知识(saveOrUpdate)和字段(整体删除再新增)
     *
     * @param knowledge
     * @param taskItem
     */
    public void save(TempKnowledge knowledge, TaskItem taskItem) {
        Knowledge dbEntity = tempKnowledgeService.getById(knowledge.getId());
        // 记录历史;
        if (Objects.nonNull(dbEntity)) {
            HistoryUtils.save(knowledge.getId(), knowledge.getName(), History.OPERATE_NEW, History.OPERATE_RESULT_SUCCESS);
        } else {
            HistoryUtils.save(knowledge.getId(), knowledge.getName(), History.OPERATE_REEDIT, History.OPERATE_RESULT_SUCCESS);
        }
        // 保存知识和字段;
        tempKnowledgeService.saveBeanAndField(JSON.parseObject(JSON.toJSONString(knowledge), TempKnowledge.class));
        // 保存任务项(name, wordsCount, nameSuggestion可能需要改动)
        taskItem.setName(knowledge.getName());
        taskItem.setWordsCount(knowledge.getKnowledgeFieldList().stream().mapToInt(KnowledgeField::getWordsCount).sum());
        taskItemService.updateById(taskItem);
    }

    /**
     * 勘误知识, step:
     * 1: 记录history(操作历史)
     * 2: 记录 lastEditedField, FieldCompare
     * 3: 保存知识(update 版本 + 1)和字段(整体删除再新增)
     * 4: 更新最近已发布任务项(名称可能修改, 统计字数)
     * 5: 维护静态资源表
     * 6: 维护历史版本
     * 7: 修改同步表
     *
     * @param knowledge
     */
    public void correct(ReleasedKnowledge knowledge, TaskItem taskItem) {
        // 记录操作历史;
        HistoryUtils.save(knowledge.getId(), knowledge.getName(), History.OPERATE_CORRECT, History.OPERATE_RESULT_SUCCESS);
        // 记录field_compare, last_edited_field;
        FieldCompareUtil.recordChangesInKnowledgeFields(History.OPERATE_CORRECT, knowledge);
        // 版本+1, 保存知识和字段;
        knowledge.setVersion(knowledge.getVersion() + 1);
        ReleasedKnowledge releasedKnowledge = JSON.parseObject(JSON.toJSONString(knowledge), ReleasedKnowledge.class);
        releasedKnowledgeService.saveBeanAndField(releasedKnowledge);
        // 保存任务项(name, wordsCount可能需要改动)
        taskItem.setName(knowledge.getName());
        taskItem.setWordsCount(knowledge.getKnowledgeFieldList().stream().mapToInt(KnowledgeField::getWordsCount).sum());
        taskItemService.updateById(taskItem);
        // 添加历史版本;
        knowledgeHistoryService.add(knowledge);
        // 同步;
        knowledgeSyncStatusService.correctKnowledge(knowledge);
        // 保存静态资源
        //fileLibService.insertKnowledgeFileLib(releasedKnowledge, releasedKnowledge.getReleasedKnowledgeFieldList());
    }

    /**
     * 知识提交审核
     * 1: 记录操作;
     * 2: 记录字段变更;
     * 3: 修改知识和字段;
     * 4: 修改任务项;
     *
     * @param knowledge
     * @param taskItem
     */
    public void commit(TempKnowledge knowledge, TaskItem taskItem) {
        // 记录操作历史;
        HistoryUtils.save(knowledge.getId(), knowledge.getName(), History.OPERATE_COMMIT, History.OPERATE_RESULT_SUCCESS);
        // 记录字段变更;
        FieldCompareUtil.recordChangesInKnowledgeFields(History.OPERATE_COMMIT, knowledge);
        // 保存知识和字段;
        tempKnowledgeService.saveBeanAndField(knowledge);
        // 修改任务项;
        Integer modifiedStatus = KnowledgeEditUtil.auditStatus(knowledge.getId(), taskItem.getAuditLevel(), "commit");
        taskItem.setStatus(modifiedStatus);
        taskItem.setName(knowledge.getName());
        taskItem.setSubmitTime(new SimpleDateFormat("yyyy-MM-dd").format(new Date()));
        taskItem.setWordsCount(knowledge.getKnowledgeFieldList().stream().mapToInt(KnowledgeField::getWordsCount).sum());
        taskItemService.updateById(taskItem);
    }

    /**
     * 审核通过(一审, 二审, 三审通过)
     * 1: 记录操作;
     * 2: 记录字段变更;
     * 3: 修改知识和字段;
     * 4: 修改任务项;
     */
    public void pass(TempKnowledge knowledge, TaskItem taskItem) {
        // 记录操作历史;
        HistoryUtils.save(knowledge.getId(), knowledge.getName(), History.OPERATE_PASS, History.OPERATE_RESULT_SUCCESS);
        // 记录字段变更;
        FieldCompareUtil.recordChangesInKnowledgeFields(History.OPERATE_PASS, knowledge);
        // 保存知识和字段;
        tempKnowledgeService.saveBeanAndField(JSON.parseObject(JSON.toJSONString(knowledge), TempKnowledge.class));
        // 修改任务项;
        Integer modifiedStatus = KnowledgeEditUtil.auditStatus(knowledge.getId(), taskItem.getAuditLevel(), "pass");
        taskItem.setStatus(modifiedStatus);
        taskItem.setName(knowledge.getName());
        taskItem.setWordsCount(knowledge.getKnowledgeFieldList().stream().mapToInt(KnowledgeField::getWordsCount).sum());
        taskItemService.updateById(taskItem);
    }

    /**
     * 审核驳回(一审, 二审, 三审驳回)
     * 1: 记录操作;
     * 2: 记录字段变更;
     * 3: 修改知识和字段;
     * 4: 修改任务项;
     */
    public void reject(TempKnowledge knowledge, TaskItem taskItem) {
        // 记录操作历史;
        HistoryUtils.save(knowledge.getId(), knowledge.getName(), History.OPERATE_REJECT, History.OPERATE_RESULT_SUCCESS);
        // 记录字段变更;
        FieldCompareUtil.recordChangesInKnowledgeFields(History.OPERATE_REJECT, knowledge);
        // 保存知识和字段;
        tempKnowledgeService.saveBeanAndField(JSON.parseObject(JSON.toJSONString(knowledge), TempKnowledge.class));
        // 修改任务项;
        Integer modifiedStatus = KnowledgeEditUtil.auditStatus(knowledge.getId(), taskItem.getAuditLevel(), "reject");
        taskItem.setStatus(modifiedStatus);
        taskItem.setName(knowledge.getName());
        taskItem.setWordsCount(knowledge.getKnowledgeFieldList().stream().mapToInt(KnowledgeField::getWordsCount).sum());
        taskItemService.updateById(taskItem);
    }

    // temp有值, 则取temp, 否则取released;
    public Knowledge getKnowledgeAndFieldById(String knowledgeId) {
        Knowledge knowledge = null;
        if (StringUtils.isNotEmpty(knowledgeId)) {
            knowledge = getTempKnowledgeAndFieldById(knowledgeId);
            if (Objects.isNull(knowledge)) {
                knowledge = getReleasedKnowledgeAndFieldById(knowledgeId);
            }
        }
        return knowledge;
    }

    public TempKnowledge getTempKnowledgeAndFieldById(String knowledgeId) {
        TempKnowledge knowledge = tempKnowledgeService.getById(knowledgeId);
        if (Objects.isNull(knowledge)) {
            return null;
        }
        List<KnowledgeField> knowledgeFields = Lists.newArrayList();
        tempKnowledgeFieldService.lambdaQuery()
                .eq(TempKnowledgeField::getKnowledgeId, knowledgeId)
                .eq(TempKnowledgeField::getHidden, 0)
                .orderByAsc(TempKnowledgeField::getId)
                .list().forEach(knowledgeFields::add);
        knowledge.setKnowledgeFieldList(knowledgeFields);
        knowledge.setKnowledgeLibName(knowledgeLibService.getById(knowledge.getKnowledgeLibId()).getName());
        // 排序
        KnowledgeEditUtil.resortKnowledgeFields(knowledge);
        return knowledge;
    }

    public ReleasedKnowledge getReleasedKnowledgeAndFieldById(String knowledgeId) {
        ReleasedKnowledge knowledge = releasedKnowledgeService.getById(knowledgeId);
        if (Objects.isNull(knowledge)) {
            return null;
        }
        // 给releasedKnowledge对象设置fields
        List<KnowledgeField> knowledgeFields = Lists.newArrayList();
        releasedKnowledgeFieldService.lambdaQuery()
                .eq(ReleasedKnowledgeField::getKnowledgeId, knowledgeId)
                .eq(ReleasedKnowledgeField::getHidden, 0)
                .orderByAsc(ReleasedKnowledgeField::getId)
                .list().forEach(knowledgeFields::add);
        knowledge.setKnowledgeFieldList(knowledgeFields);
        knowledge.setKnowledgeLibName(knowledgeLibService.getById(knowledge.getKnowledgeLibId()).getName());
        // 排序
        KnowledgeEditUtil.resortKnowledgeFields(knowledge);
        return knowledge;
    }

    /**
     * 取消发布修改History表的操作动作和结果
     *
     * @return
     */
    private int updateHistory(String tempid, String releaseid) {

        historyMapper.executeUpdate("update history set  knowledge_id='" + releaseid + "'  where knowledge_id='" + tempid + "'");
        return 1;
    }


    public TempKnowledge addRelease2Temp(TempKnowledge tempKnowledge, String id,
                                         List<TempKnowledgeField> tempKnowledgeFields) {
        //deleteReleaseknowledgeAndField(id);
        tempKnowledgeService.save(tempKnowledge);
        tempKnowledgeFields.forEach(field -> field.setKnowledgeId(tempKnowledge.getId()));
        tempKnowledgeFieldService.saveOrUpdateBatch(tempKnowledgeFields);
        // deleteByhistoryid(id);
        updateHistory(id, tempKnowledge.getId());
        return tempKnowledge;
    }


    public TempKnowledge importTempKnowledge(String filePath, String fileName, String knowledgeLibId, ActivityItem activityItem) {
        String knowledgeName = fileName;
        // 知识名称重复性校验;
        List<TempKnowledge> dbTempKnowledgeList = tempKnowledgeService.lambdaQuery().eq(TempKnowledge::getKnowledgeLibId, knowledgeLibId).eq(TempKnowledge::getName, knowledgeName).list();
        List<ReleasedKnowledge> dbReleasedKnowledgeList = releasedKnowledgeService.lambdaQuery().eq(ReleasedKnowledge::getKnowledgeLibId, knowledgeLibId).eq(ReleasedKnowledge::getName, knowledgeName).list();

        if (CollectionUtils.isNotEmpty(dbTempKnowledgeList) || CollectionUtils.isNotEmpty(dbReleasedKnowledgeList)) {
            // 异常信息;
            log.error("word导入:" + knowledgeName + "已存在, 未导入");
            return null;
        }
        String htmlPath = WordToHtmlUtil.Word2007ToHtml(filePath);
        String htmlStr = null;
        try {
            htmlStr = FileUtils.readFileToString(new File(htmlPath));
        } catch (IOException e) {
            throw new RuntimeException("读取word文件失败");
        }
        htmlStr = htmlStr.replaceAll("<br/>", "</p><p>");
        Document htmlDoc = Jsoup.parse(htmlStr);

        TempKnowledge knowledge = new TempKnowledge();
        knowledge.setKnowledgeLibId(knowledgeLibId);
        knowledge.setName(knowledgeName);
        // 保存知识;
        tempKnowledgeService.save(knowledge);
        // 知识库字段列表, 有序;
        String sql = "select * from knowledge_lib_field where knowledge_lib_id = '" + knowledgeLibId + "' order by `index`";
        List<KnowledgeLibField> KnowledgeLibFieldList = knowledgeLibService.getKnowledgeLibField(sql);
        // html转tempKnowledge;
        knowledge = parseHtmlToTempKnowledge(htmlDoc, knowledgeLibId, KnowledgeLibFieldList, knowledge, activityItem);

        knowledge.setName(knowledge.getKnowledgeFieldList().get(0).getProperty());
        TempKnowledge tempKnowledge = tempKnowledgeService.getBaseMapper().saveBean(knowledge);

        activityItem.setKnowledgeId(tempKnowledge.getId());
        activityItem.setStatus(ActivityItem.UNDISTRIBUTED);
        activityItemService.update(Wrappers.lambdaUpdate(ActivityItem.class)
                .set(ActivityItem::getKnowledgeId, tempKnowledge.getId())
                .set(ActivityItem::getFailureReason, " ")
                .set(ActivityItem::getStatus, ActivityItem.UNDISTRIBUTED)
                .eq(ActivityItem::getId, activityItem.getId()));

        knowledge.getKnowledgeFieldList().stream().distinct()
                .forEach(item -> tempKnowledgeFieldService.saveOrUpdate((TempKnowledgeField) item));
        return knowledge;
    }

    private TempKnowledge parseHtmlToTempKnowledge(Document htmlDoc, String knowledgeLibId, List<KnowledgeLibField> KnowledgeLibFieldList, TempKnowledge knowledge, ActivityItem activityItem) {
        Elements contentEls = htmlDoc.body().child(0).children();
        List<KnowledgeField> fieldList = new ArrayList<>();
        Map<String, String> fieldMap = new HashMap<>();
        String sql = " select * from knowledge_lib_field where knowledge_lib_id='0001AA100000000WD711' order by `index`";
        List<KnowledgeLibField> knowledgeLibField = knowledgeLibService.getKnowledgeLibField(sql);
        TempKnowledgeField field = new TempKnowledgeField();
        TempKnowledgeField quField = new TempKnowledgeField();
        TempKnowledge tempKnowledge1 = null;
        TempKnowledgeField tempField = null;
        if (!contentEls.get(0).text().startsWith("#")) {
            contentEls.remove(0);
        }
        for (int i = 0; i < contentEls.size(); i++) {
            Element currentEl = contentEls.get(i);
            // 如果是空, 跳过,
            if (StringUtil.isEmpty(currentEl.text())
                    && currentEl.getElementsByTag("img").size() == 0
                    && currentEl.getElementsByTag("table").size() == 0) {
                continue;
            }
            // 如果当前元素为表格, 则应该把表格直接插入到field中, 并把当前元素指向下一元素;
            if (Objects.equals(currentEl.tag().getName(), "table")) {
                currentEl.getAllElements().forEach(el -> el.removeAttr("class").removeAttr("style"));
                currentEl.getElementsByTag("td").forEach(td -> td.text(td.text()));
                currentEl.attr("border", "1px solid black");
                currentEl.attr("cellspacing", "0");
                if (StringUtils.isNotBlank(field.getProperty())) {
                    field.setProperty(field.getProperty() + currentEl.toString());
                } else {
                    field.setProperty(currentEl.toString());
                }
                continue;
            }
            String currentContent = currentEl.text().trim().replace(" ", "");
            // 以#开头, 则证明是一个新字段;
            if (currentContent.startsWith("#") || currentContent.startsWith("*")) {
                //如果是 #常见问题汇总 就代表是问答库
                if (currentContent.startsWith("#常见问题汇总")) {
                    continue;
                }
                if (currentContent.startsWith("*问题")) {
                    TempKnowledge tempKnowledge = new TempKnowledge();
                    tempKnowledge.setName(currentEl.text());
                    tempKnowledge.setKnowledgeLibId("0001AA100000000WD711");
                    tempKnowledgeService.getBaseMapper().saveBean(tempKnowledge);

                    tempKnowledge1 = tempKnowledge;
                    tempField = new TempKnowledgeField();
                    quField.setName("*问题");
                    continue;
                }
                if (currentContent.startsWith("*答案")) {
                    quField.setName("*答案");
                    continue;
                }
                currentContent = currentContent.substring(1).replaceAll(" ", "");
                field = new TempKnowledgeField();
                field.setKnowledgeId(knowledge.getId());
                field.setName(currentContent);
                field.setDisplayName(field.getName());
                for (KnowledgeLibField libField : KnowledgeLibFieldList) {
                    if (StringUtils.equals(libField.getName(), currentContent)) {
                        field.setKind(libField.getKind());
                        field.setKindValue(libField.getKindValue());
                        field.setKindValue(libField.getKindValue());
                        if (libField.getKind() == KnowledgeLibField.FIELD_KIND_ASSOCIATE_CURRENT_KNOWLEDGE_LIB) {
                            field.setKnowledgeLibId(libField.getKnowledgeLibId());
                        } else {
                            field.setKnowledgeLibId(libField.getKindValue());
                        }
                        break;
                    } else {
                        field.setKind(1);
                    }
                }
                fieldList.add(field);
            }
            // 否则还是属于上一个字段的内容;
            else {
                // 如果是富文本;
                if (field.getKind() == KnowledgeLibField.FIELD_KIND_RICHEDITOR && StringUtils.isBlank(quField.getName())) {
                    // 如果包含图片;
                    Elements imgEls = currentEl.getElementsByTag("img");
                    if (imgEls.size() > 0 || currentEl.getElementsByTag("table").size() > 0) {
                        //如果是表格
                        if (currentEl.getElementsByTag("table").size() > 0) {
                            currentEl.getAllElements().forEach(el -> el.removeAttr("class").removeAttr("style"));
                            currentEl.getElementsByTag("td").forEach(td -> td.text(td.text()));
                            currentEl.attr("border", "1px solid black");
                            currentEl.attr("cellspacing", "0");
                            if (StringUtils.isNoneBlank(field.getProperty())) {
                                field.setProperty(field.getProperty() + currentEl.toString());
                            } else {
                                field.setProperty(currentEl.toString());
                            }
                            continue;
                        }
                        String targetImgName = imgEls.get(0).attr("src").substring(imgEls.get(0).attr("src").lastIndexOf("/") + 1);

                        // 如果上一行以"表"字开头, 则渲染为表题;
                        if (contentEls.get(i - 1).text().startsWith("表")) {
                            Element imgTitle = new Element("p");
                            imgTitle.addClass("t_title");
                            imgTitle.attr("id", "t_title_" + targetImgName.substring(0, targetImgName.lastIndexOf(".")));
                            imgTitle.html(JsoupUtil.getElementTextContainSupAndSub(currentEl.previousElementSibling()));

                            Document fieldContent = Jsoup.parse(field.getProperty());
                            fieldContent.getElementsByTag("body").get(0).children().last().remove();
                            fieldContent.append(imgTitle.toString());
                            field.setProperty(fieldContent.toString());

                        }
                        for (Element img : imgEls) {
                            String imgSrc = img.attr("src");
                            targetImgName = imgSrc.substring(imgSrc.lastIndexOf("/") + 1);
                            Element imgElement = new Element("img");
                            imgElement.attr("id", targetImgName.substring(0, targetImgName.lastIndexOf(".")));
                            imgElement.attr("src", "/ymer/action/file/showImage?filename=image/knowledge/" + knowledgeLibId + "/" + knowledge.getId() + "/" + targetImgName);
                            imgElement.attr("title", "插图");
                            imgElement.addClass("rw_img picture");
                            if (StringUtils.isNoneBlank(field.getProperty())) {
                                field.setProperty(field.getProperty() + "<p>" + imgElement.toString() + "</p>");
                            } else {
                                field.setProperty("<p>" + imgElement.toString() + "</p>");

                            }
                            File imgFile = new File(imgSrc);
                            if (imgFile.exists()) {
                                // 移动图片;
                                String dir = ApplicationContextUtil.BASE_DOWN_FORDER + "image/knowledge/" + knowledgeLibId + "/" + knowledge.getId();
                                File targetDir = new File(dir);
                                if (!targetDir.exists()) {
                                    //如果该项目名称文件夹未创建，则创建
                                    targetDir.mkdirs();
                                }
                                imgFile.renameTo(new File(dir + File.separator + targetImgName));
                            }
                        }
                        //如果下一行以"图"字开头, 则说明是图题;
                        if (contentEls.get(i + 1).text().startsWith("图")) {
                            i += 1;
                            currentEl = contentEls.get(i);
                            String substring = currentEl.text().trim().substring(currentEl.text().trim().indexOf("：") + 1);
                            Element imgTitle = new Element("p");
                            imgTitle.addClass("p_title");
                            imgTitle.attr("id", "p_title_" + targetImgName.substring(0, targetImgName.lastIndexOf(".")));
                            imgTitle.html(substring);
                            field.setProperty(field.getProperty() + imgTitle.toString());
                            continue;
                        }
                    }
                    // 不是图片;
                    else {
                        String str = "<p>" + JsoupUtil.getElementContentTextSupAndSub(currentEl) + "</p>";

                        Pattern pattern = Pattern.compile("^[0-9]+");
                        Pattern pattern1 = Pattern.compile("\\（[0-9]+\\）");
                        Pattern pattern2 = Pattern.compile("\\([0-9]+\\)");
                        if (pattern.matcher(StringUtils.deleteWhitespace(currentEl.text())).find()) {
                            if (currentEl.getElementsByTag("span").size() > 0 && currentEl.getElementsByTag("span").get(currentEl.getElementsByTag("span").size() - 1).attr("style").contains("font-weight")) {
                                str = "<p class='h1'>" + JsoupUtil.getElementTextContainSupAndSub(currentEl) + "</p>";
                            } else {
                                str = "<p>" + JsoupUtil.getElementContentTextSupAndSub(currentEl) + "</p>";
                            }
                        } else if (pattern1.matcher(StringUtils.deleteWhitespace(currentEl.text())).find() || pattern2.matcher(StringUtils.deleteWhitespace(currentEl.text())).find()) {
                            if (currentEl.getElementsByTag("span").size() > 0 && currentEl.getElementsByTag("span").get(currentEl.getElementsByTag("span").size() - 1).attr("style").contains("font-weight")) {
                                str = "<p class='h2'>" + JsoupUtil.getElementTextContainSupAndSub(currentEl) + "</p>";
                            } else {
                                str = "<p>" + JsoupUtil.getElementContentTextSupAndSub(currentEl) + "</p>";
                            }
                        }
                        if (StringUtils.isNotBlank(field.getProperty())) {
                            field.setProperty(field.getProperty());
                        } else {
                            field.setProperty(str);
                        }
                    }
                }
                // 如果是输入框;
                else if (field.getKind() == KnowledgeLibField.FIELD_KIND_STRINGTEXT) {
                    if (StringUtils.isEmpty(field.getProperty())) {
                        field.setProperty(currentContent.trim());
                    } else {
                        field.setProperty(field.getProperty() + ", " + currentContent.trim());
                    }
                    fieldMap.put("name", currentContent.trim());
                    //如果是分类
                } else if (field.getKind() == KnowledgeLibField.FIELD_KIND_REFERENCE) {
                    String tagStr = currentContent;
                    String[] split = tagStr.split("\\|");
                    String name = Arrays.stream(split).map(String::toString).collect(Collectors.joining("','", "('", "')"));
                    List<Tag> tagList = tagService.getTagName(name, field.getKindValue());
                    List<String> list = new ArrayList<>();
                    int index = 1;
                    if (tagList.size() > 0) {
                        for (int j = 0; j < split.length; j++) {
                            index = ++index;
                            if (tagList.get(j).getLevel() == index)
                                list.add(tagList.get(j).getId());
                        }
                    }
                    String tagId = "";
                    if (list.size() > 0) {
                        tagId = list.stream().map(String::toString).collect(Collectors.joining("\",\"", "[[\"", "\"]]"));
                        if (StringUtils.isNoneBlank(field.getProperty())) {
                            JSONArray objects = JSONArray.parseArray(field.getProperty()).fluentAddAll(JSONArray.parseArray(tagId));
                            tagId = objects.stream().map(JSON::toJSONString).collect(Collectors.joining(",", "[", "]"));
                            field.setProperty(tagId);
                        } else {
                            field.setProperty(tagId);

                        }
                    }
                    fieldMap.put("tagId", tagId);
                    fieldMap.put("tag", field.getKindValue());
                    //多值输入框
                } else if (field.getKind() == KnowledgeLibField.FIELD_KIND_MULTI_VALUE_INPUT) {
                    String multiValue = JsoupUtil.getElementTextContainSupAndSub(currentEl).replace(" ", "");
                    String[] split = multiValue.split("\\|");
                    List<String> list = new ArrayList<>();
                    for (int j = 0; j < split.length; j++) {
                        String stringSplit = split[j];
                        list.add(stringSplit);
                    }
                    multiValue = list.stream().collect(Collectors.joining("\",\"", "[\"", "\"]"));
                    field.setProperty(multiValue);
                    //文本域
                } else if (field.getKind() == KnowledgeLibField.FIELD_KIND_TEXTAREA) {
                    if (StringUtils.isEmpty(field.getProperty())) {
                        field.setProperty(currentEl.text().trim());
                    } else {
                        field.setProperty(field.getProperty() + currentEl.text().trim());
                    }
                    //单选下拉框
                } else if (field.getKind() == KnowledgeLibField.FIELD_KIND_DROPDOWNLIST) {
                    String wherePart = " name='" + currentContent.trim() + "' and id='" + field.getKindValue() + "'";
                    List<RuleItem> ruleItem = ruleItemService.getRuleItem(wherePart);
                    if (ruleItem.size() > 0) {
                        field.setProperty(ruleItem.get(0).getId());
                    }
                    //多选下拉框
                } else if (field.getKind() == KnowledgeLibField.FIELD_KIND_DROPMULTILIST) {
                    String ruleItemValue = currentEl.text().trim().replace("；", ";");
                    String[] split = ruleItemValue.split("、");
                    List<String> list = new ArrayList<>();
                    String name = Arrays.stream(split).map(String::toString).collect(Collectors.joining("','", "('", "')"));
                    String wherePart = " name in" + name + " and rule_id='" + field.getKindValue() + "'";
                    List<RuleItem> ruleItems = ruleItemService.getRuleItem(wherePart);
                    for (RuleItem ruleItem : ruleItems) {
                        list.add(ruleItem.getId());
                    }
                    if (list.size() > 0) {
                        ruleItemValue = list.stream().collect(Collectors.joining("\",\"", "[\"", "\"]"));
                        field.setProperty(ruleItemValue);
                    }
                } else if (field.getKind() == KnowledgeLibField.FIELD_KIND_ASSOCIATE_CURRENT_KNOWLEDGE_LIB) {
                    String kowledgeName = JsoupUtil.getElementTextContainSupAndSub(currentEl).replace(" ", "");
                    String[] split = kowledgeName.split(";");
                    List<Map<String, Object>> list = new ArrayList<>();
                    String name = Arrays.stream(split).map(String::toString).collect(Collectors.joining("','", "('", "')"));
                    List<TempKnowledge> tempKnowledges = tempKnowledgeService.getBaseMapper().selectBeansByWherePart(" name in " + name + " and knowledge_lib_id='" + field.getKnowledgeLibId() + "'");
                    List<ReleasedKnowledge> releasedKnowledges = releasedKnowledgeService.getBaseMapper().selectBeansByWherePart(" name in " + name + " and knowledge_lib_id='" + field.getKnowledgeLibId() + "'");
                    if (tempKnowledges.size() > 0) {
                        for (TempKnowledge tempKnowledge : tempKnowledges) {
                            Map<String, Object> map = new HashMap<>();
                            map.put("name", tempKnowledge.getName());
                            map.put("id", tempKnowledge.getId());
                            list.add(map);
                        }
                    }
                    if (releasedKnowledges.size() > 0) {
                        for (ReleasedKnowledge releasedKnowledge : releasedKnowledges) {
                            Map<String, Object> map = new HashMap<>();
                            map.put("name", releasedKnowledge.getName());
                            map.put("id", releasedKnowledge.getId());
                            list.add(map);
                        }
                    }
                    String json = JSONArray.toJSONString(list);
                    field.setProperty(json);
                } else if (field.getKind() == KnowledgeLibField.FIELD_KIND_ASSOCIATE_OTHER_KNOWLEDGE_LIB) {
                    String kowledgeName = JsoupUtil.getElementTextContainSupAndSub(currentEl).replace(" ", "");
                    String[] split = kowledgeName.split(";");
                    List<Map<String, Object>> list = new ArrayList<>();
                    String name = Arrays.stream(split).map(String::toString).collect(Collectors.joining("','", "('", "')"));
                    List<TempKnowledge> tempKnowledges = tempKnowledgeService.getBaseMapper().selectBeansByWherePart(" name in " + name + " and knowledge_lib_id='" + field.getKnowledgeLibId() + "'");
                    List<ReleasedKnowledge> releasedKnowledges = releasedKnowledgeService.getBaseMapper().selectBeansByWherePart(" name in " + name + " and knowledge_lib_id='" + field.getKnowledgeLibId() + "'");
                    if (tempKnowledges.size() > 0) {
                        for (TempKnowledge tempKnowledge : tempKnowledges) {
                            Map<String, Object> map = new HashMap<>();
                            map.put("name", tempKnowledge.getName());
                            map.put("id", tempKnowledge.getId());
                            list.add(map);
                        }
                    }
                    if (releasedKnowledges.size() > 0) {
                        for (ReleasedKnowledge releasedKnowledge : releasedKnowledges) {
                            Map<String, Object> map = new HashMap<>();
                            map.put("name", releasedKnowledge.getName());
                            map.put("id", releasedKnowledge.getId());
                            list.add(map);
                        }
                    }
                    String json = JSONArray.toJSONString(list);
                    field.setProperty(json);
                    //图片
                } else if (field.getKind() == KnowledgeLibField.FIELD_KIND_IMG) {

                    if (contentEls.get(i).text().startsWith("图")) {
                        String substring = currentEl.text().trim().substring(currentEl.text().trim().lastIndexOf("：") + 1);
                        Map<String, String> value = JSON.parseObject(field.getProperty(), Map.class);
                        value.put("title", substring);
                        String string = JSON.toJSONString(value);
                        field.setProperty(string);
                        continue;
                    }
                    //如果下一行以"图"字开头, 则说明是图题;
                    Elements imgEls = currentEl.getElementsByTag("img");
                    if (imgEls.size() > 0) {
                        Map<String, Object> map = new HashMap<>();
                        List<String> list = new ArrayList();
                        String jsonImg = "";
                        for (Element img : imgEls) {
                            String imgSrc = img.attr("src");
                            String targetImgName = imgSrc.substring(imgSrc.lastIndexOf("/") + 1);
                            String src = "/ymer/action/file/showImage?filename=image/knowledge/" + knowledgeLibId + "/" + knowledge.getId() + "/" + targetImgName;
                            if (StringUtils.isNoneBlank(field.getProperty())) {
                                JSONObject jsonObject = JSON.parseObject(field.getProperty());
                                jsonObject.getJSONArray("paths").add(src);
                                jsonImg = JSON.toJSONString(jsonObject);
                            } else {
                                list.add(src);
                                map.put("paths", list);
                                map.put("additional", "");
                                map.put("comment", "");
                                String aClass = img.attr("class");
                                if ("".equals(aClass)) {
                                    aClass = "";
                                }
                                map.put("type", aClass);
                                map.put("classification", "");
                                map.put("title", "");
                                jsonImg = JSONObject.toJSONString(map);
                            }
                            File imgFile = new File(imgSrc);
                            if (imgFile.exists()) {
                                // 移动图片;
                                String dir = ApplicationContextUtil.BASE_DOWN_FORDER + "image/knowledge/" + knowledgeLibId + "/" + knowledge.getId();
                                File targetDir = new File(dir);
                                if (!targetDir.exists()) {
                                    //如果该项目名称文件夹未创建，则创建
                                    targetDir.mkdirs();
                                }
                                imgFile.renameTo(new File(dir + File.separator + targetImgName));
                            }
                        }
                        field.setProperty(jsonImg);
                    }
                    if (currentEl.text().trim().startsWith("无")) {
                        field.setProperty("{\"paths\":[],\"additional\":\"\",\"comment\":\"\",\"type\":\"\",\"classification\":\"\",\"title\":\"\"}");
                    }
                } else if (field.getKind() == KnowledgeLibField.FIELD_KIND_VIDEO) {
                    if (currentEl.text().trim().startsWith("无") || StringUtils.isBlank(currentEl.text().trim())) {
                        field.setProperty("{\"paths\":[],\"type\":\"\",\"title\":\"\"}");
                    }
                }
                if (Objects.nonNull(field)) {
                    fieldList.add(field);
                }
                //问答库
                if (StringUtils.equals(quField.getName(), "*问题")) {
                    TempKnowledgeField tempKnowledgeField = new TempKnowledgeField();
                    tempKnowledgeField.setName("名称");
                    tempKnowledgeField.setKind(KnowledgeLibField.FIELD_KIND_STRINGTEXT);
                    tempKnowledgeField.setProperty(currentEl.text());
                    tempKnowledgeField.setKnowledgeId(tempKnowledge1.getId());
                    tempKnowledgeField.setIndex(0);
                    tempKnowledgeField.setKnowledgeLibFieldId(knowledgeLibField.get(0).getId());
                    tempKnowledgeFieldService.saveOrUpdate(tempKnowledgeField);
                    //修改知识名称
                    tempKnowledge1.setName(currentEl.text());
                    tempKnowledgeService.saveOrUpdate(tempKnowledge1);
                    //新增问答库活动详情
                    ActivityItem item = new ActivityItem();
                    item.setKnowledgeName(tempKnowledge1.getName());
                    item.setKnowledgeId(tempKnowledge1.getId());
                    item.setKnowledgeLibId(Const.QW_LIB_ID);
                    item.setActivityId(activityItem.getActivityId());
                    item.setStatus(ActivityItem.UNDISTRIBUTED);
                    item.setPath(activityItem.getPath());
                    item.setDeleted(ActivityItem.DELETED_NO);
                    item.setManuscriptName(activityItem.getManuscriptName());
                    activityItemService.getBaseMapper().saveBean(item);

                    TempKnowledgeField disease = new TempKnowledgeField();
                    disease.setName("关联疾病");
                    disease.setProperty(fieldMap.get("name"));
                    disease.setKind(KnowledgeLibField.FIELD_KIND_STRINGTEXT);
                    disease.setKnowledgeId(tempKnowledge1.getId());
                    disease.setIndex(1);
                    disease.setKnowledgeLibFieldId(knowledgeLibField.get(1).getId());
                    tempKnowledgeFieldService.saveOrUpdate(disease);

                    TempKnowledgeField department = new TempKnowledgeField();
                    department.setName("科室");
                    department.setProperty(fieldMap.get("tagId"));
                    department.setKindValue(fieldMap.get("tag"));

                    department.setKind(KnowledgeLibField.FIELD_KIND_REFERENCE);
                    department.setKnowledgeId(tempKnowledge1.getId());
                    department.setIndex(3);
                    tempKnowledgeFieldService.saveOrUpdate(department);
                }
                if (StringUtils.equals(quField.getName(), "*答案")) {
                    String str = "<p>" + JsoupUtil.getElementTextContainSupAndSub(currentEl) + "</p>";
                    Pattern pattern = Pattern.compile("^[0-9]+");
                    Pattern pattern1 = Pattern.compile("\\（[0-9]+\\）");
                    Pattern pattern2 = Pattern.compile("\\([0-9]+\\)");

                    if (pattern.matcher(StringUtils.deleteWhitespace(currentEl.text())).find()) {
                        if (currentEl.getElementsByTag("span").size() > 0 && currentEl.getElementsByTag("span").get(currentEl.getElementsByTag("span").size() - 1).attr("style").contains("font-weight")) {
                            str = "<p class='h1'>" + JsoupUtil.getElementTextContainSupAndSub(currentEl) + "</p>";
                        } else {
                            str = "<p>" + JsoupUtil.getElementTextContainSupAndSub(currentEl) + "</p>";
                        }
                    } else if (pattern1.matcher(StringUtils.deleteWhitespace(currentEl.text())).find() || pattern2.matcher(StringUtils.deleteWhitespace(currentEl.text())).find()) {
                        if (currentEl.getElementsByTag("span").size() > 0 && currentEl.getElementsByTag("span").get(currentEl.getElementsByTag("span").size() - 1).attr("style").contains("font-weight")) {
                            str = "<p class='h2'>" + JsoupUtil.getElementTextContainSupAndSub(currentEl) + "</p>";
                        } else {
                            str = "<p>" + JsoupUtil.getElementTextContainSupAndSub(currentEl) + "</p>";
                        }
                    }
                    tempField.setName("答案");
                    tempField.setKnowledgeLibFieldId(knowledgeLibField.get(2).getId());
                    tempField.setKind(KnowledgeLibField.FIELD_KIND_RICHEDITOR);
                    if (StringUtils.isNotBlank(tempField.getProperty())) {
                        tempField.setProperty(tempField.getProperty() + str);
                    } else {
                        tempField.setProperty(str);
                    }
                    tempField.setKnowledgeId(tempKnowledge1.getId());
                    tempField.setIndex(2);
                    tempKnowledgeFieldService.saveOrUpdate(tempField);
                }
            }
        }

        knowledge.setKnowledgeFieldList(fieldList);
        return knowledge;
    }

    public TempKnowledge importTempKnowledge1(String filePath, String fileName, String knowledgeLibId, String taskId, String questionAnswerTaskId) {

        String htmlPath = WordToHtmlUtil.Word2007ToHtml(filePath);
        String htmlStr = null;
        try {
            htmlStr = FileUtils.readFileToString(new File(htmlPath));
        } catch (IOException e) {
            throw new RuntimeException("读取文件失败");
        }
        htmlStr = htmlStr.replaceAll("<br/>", "</p><p>").replaceAll("%1", "1");
        Document htmlDoc = Jsoup.parse(htmlStr);

        TempKnowledge knowledge = new TempKnowledge();
        knowledge.setKnowledgeLibId(knowledgeLibId);
        // 保存知识;
        tempKnowledgeService.save(knowledge);
        // 知识库字段列表, 有序;
        List<KnowledgeLibField> knowledgeLibFieldList = knowledgeLibFieldService.lambdaQuery()
                .eq(KnowledgeLibField::getKnowledgeLibId, knowledgeLibId).orderByAsc(KnowledgeLibField::getIndex)
                .list();
        // html转tempKnowledge;
        knowledge = parseHtmlToTempKnowledge1(htmlDoc, knowledgeLibId, knowledgeLibFieldList, knowledge, questionAnswerTaskId);
        knowledge.setName(knowledge.getKnowledgeFieldList().get(0).getProperty());
        // 知识名称重复性校验;
        List<TempKnowledge> dbTempKnowledgeList = tempKnowledgeService.lambdaQuery().eq(TempKnowledge::getKnowledgeLibId, knowledgeLibId).eq(TempKnowledge::getName, knowledge.getName()).list();
        List<ReleasedKnowledge> dbReleasedKnowledgeList = releasedKnowledgeService.lambdaQuery().eq(ReleasedKnowledge::getKnowledgeLibId, knowledgeLibId).eq(ReleasedKnowledge::getName, knowledge.getName()).list();

        if (CollectionUtils.isNotEmpty(dbTempKnowledgeList) || CollectionUtils.isNotEmpty(dbReleasedKnowledgeList)) {
            if (CollectionUtils.isNotEmpty(dbTempKnowledgeList)) {
                List<String> tempKnowledgeIds = dbTempKnowledgeList.stream().map(TempKnowledge::getId).collect(Collectors.toList());
                tempKnowledgeFieldService.remove(Wrappers.lambdaQuery(TempKnowledgeField.class).in(TempKnowledgeField::getKnowledgeId, tempKnowledgeIds));
                taskItemService.remove(Wrappers.lambdaQuery(TaskItem.class).in(TaskItem::getKnowledgeId, tempKnowledgeIds));
                tempKnowledgeService.removeByIds(tempKnowledgeIds);
            } else {
                tempKnowledgeService.removeById(knowledge.getId());
                // 异常信息;
                log.error("word导入:" + knowledge.getKnowledgeFieldList().get(0).getProperty() + "已存在, 未导入");
                return null;
            }
        }

        TempKnowledge tempKnowledge = tempKnowledgeService.getBaseMapper().saveBean(knowledge);
        Map<String, KnowledgeLibField> libFieldMap = knowledgeLibFieldList.stream()
                .collect(Collectors.toMap(KnowledgeLibField::getName, field -> field, (k1, k2) -> k1, LinkedHashMap::new));

        List<KnowledgeField> wordFieldList = knowledge.getKnowledgeFieldList().stream().distinct().collect(Collectors.toList());
        List<String> wordFieldNameList = wordFieldList.stream().map(KnowledgeField::getName).collect(Collectors.toList());
        // 存储库里有，word缺少的固定字段
        knowledgeLibFieldList.stream().filter(t -> !wordFieldNameList.contains(t.getName())).forEach(t -> {
            TempKnowledgeField tkf = JSON.parseObject(JSON.toJSONString(t), TempKnowledgeField.class);
            tkf.setId(null);
            tkf.setKind(Integer.valueOf(t.getKind()));
            tkf.setKnowledgeId(tempKnowledge.getId());
            tkf.setKnowledgeLibFieldId(t.getId());
            tempKnowledgeFieldService.save(tkf);
        });

        for (KnowledgeField kf : wordFieldList) {
            KnowledgeLibField knowledgeLibField = libFieldMap.get(kf.getName());
            TempKnowledgeField tkf = JSON.parseObject(JSON.toJSONString(kf), TempKnowledgeField.class);
            tkf.setKnowledgeId(tempKnowledge.getId());
            tkf.setName(kf.getName());
            // 固定字段
            if (Objects.nonNull(knowledgeLibField)) {
                tkf.setKnowledgeLibFieldId(knowledgeLibField.getId());
            }
            tempKnowledgeFieldService.save(tkf);
        }

        int count = countTheNumberOfWords(tempKnowledge.getId());
        TaskItem taskItem = new TaskItem();
        taskItem.setTaskId(taskId);
        taskItem.setWordsCount(count);
        taskItem.setName(tempKnowledge.getName());
        taskItem.setKnowledgeId(tempKnowledge.getId());
        taskItemService.save(taskItem);

        return knowledge;
    }

    private TempKnowledge parseHtmlToTempKnowledge1(Document htmlDoc, String knowledgeLibId, List<KnowledgeLibField> KnowledgeLibFieldList, TempKnowledge knowledge, String questionAnswerTaskId) {

        Elements contentEls = htmlDoc.body().child(0).children();
        List<KnowledgeField> fieldList = new ArrayList<>();
        Map<String, String> fieldMap = new HashMap<>();
        String sql = " select * from knowledge_lib_field where knowledge_lib_id='" + Const.QW_LIB_ID + "' order by `index`";
        List<KnowledgeLibField> knowledgeLibField = knowledgeLibService.getKnowledgeLibField(sql);
        TempKnowledgeField field = new TempKnowledgeField();
        TempKnowledgeField quField = new TempKnowledgeField();
        TempKnowledge tempKnowledge1 = null;
        TempKnowledgeField tempField = null;
        if (!contentEls.get(0).text().startsWith("#")) {
            contentEls.remove(0);
        }
        for (int i = 0; i < contentEls.size(); i++) {
            Element currentEl = contentEls.get(i);
            // 如果是空, 跳过,
            if (StringUtil.isEmpty(currentEl.text())
                    && currentEl.getElementsByTag("img").size() == 0
                    && currentEl.getElementsByTag("table").size() == 0) {
                continue;
            }
            // 如果当前元素为表格, 则应该把表格直接插入到field中, 并把当前元素指向下一元素;
            if (Objects.equals(currentEl.tag().getName(), "table")) {
                currentEl.getAllElements().forEach(el -> el.removeAttr("class").removeAttr("style"));
                currentEl.getElementsByTag("td").forEach(td -> td.text(td.text()));
                currentEl.attr("border", "1px solid black");
                currentEl.attr("cellspacing", "0");
                if (StringUtils.isNotBlank(field.getProperty())) {
                    field.setProperty(field.getProperty() + currentEl.toString());
                } else {
                    field.setProperty(currentEl.toString());
                }
                continue;
            }
            String currentContent = currentEl.text().trim().replace(" ", "");
            // 以#开头, 则证明是一个新字段;
            if (currentContent.startsWith("#") || currentContent.startsWith("*")) {
                //如果是 #常见问题汇总 就代表是问答库
                if (currentContent.startsWith("#常见问题汇总")) {
                    continue;
                }
                if (currentContent.startsWith("*问题")) {
                    TempKnowledge tempKnowledge = new TempKnowledge();
                    tempKnowledge.setName(currentEl.text());
                    tempKnowledge.setKnowledgeLibId(Const.QW_LIB_ID);
                    tempKnowledgeService.getBaseMapper().saveBean(tempKnowledge);

                    tempKnowledge1 = tempKnowledge;
                    tempField = new TempKnowledgeField();
                    quField.setName("*问题");
                    continue;
                }
                if (currentContent.startsWith("*答案")) {
                    quField.setName("*答案");
                    continue;
                }
                currentContent = currentContent.substring(1).replaceAll(" ", "");
                field = new TempKnowledgeField();
                field.setKnowledgeId(knowledge.getId());
                field.setName(currentContent);
                field.setDisplayName(field.getName());
                for (int j = 0; j < KnowledgeLibFieldList.size(); j++) {
                    KnowledgeLibField libField = KnowledgeLibFieldList.get(j);
                    if (StringUtils.equals(libField.getName(), currentContent)) {
                        field.setKind(libField.getKind());
                        field.setKnowledgeLibFieldId(libField.getId());
                        field.setKindValue(libField.getKindValue());
                        field.setKindValue(libField.getKindValue());
                        field.setIndex(j);
                        if (libField.getKind() == KnowledgeLibField.FIELD_KIND_ASSOCIATE_CURRENT_KNOWLEDGE_LIB) {
                            field.setKnowledgeLibId(libField.getKnowledgeLibId());
                        } else {
                            field.setKnowledgeLibId(libField.getKindValue());
                        }
                        break;
                    } else {
                        field.setKind(1);
                    }
                }
                fieldList.add(field);
            }
            // 否则还是属于上一个字段的内容;
            else {
                if (StringUtils.equals(StringUtils.deleteWhitespace(currentEl.text()), "无")) {
                    continue;
                }
                // 如果是富文本;
                if (field.getKind() == null) {
                    throw new RuntimeException("没找到对应的字段类型");
                }
                if (field.getKind() == KnowledgeLibField.FIELD_KIND_RICHEDITOR && StringUtils.isBlank(quField.getName())) {
                    // 如果包含图片;
                    Elements imgEls = currentEl.getElementsByTag("img");
                    if (imgEls.size() > 0 || currentEl.getElementsByTag("table").size() > 0) {
                        if (StringUtils.isNoneBlank(field.getProperty())) {
                            field.setProperty(field.getProperty() + currentContent);
                        } else {
                            field.setProperty(currentContent);
                        }
                        //如果是表格
                        if (currentEl.getElementsByTag("table").size() > 0) {
                            currentEl.getAllElements().forEach(el -> el.removeAttr("class").removeAttr("style"));
                            currentEl.getElementsByTag("td").forEach(td -> td.text(td.text()));
                            currentEl.attr("border", "1px solid black");
                            currentEl.attr("cellspacing", "0");
                            if (StringUtils.isNoneBlank(field.getProperty())) {
                                field.setProperty(field.getProperty() + currentEl.toString());
                            } else {
                                field.setProperty(currentEl.toString());
                            }
                            continue;
                        }
                        String targetImgName = imgEls.get(0).attr("src").substring(imgEls.get(0).attr("src").lastIndexOf("/") + 1);

                        // 如果上一行以"表"字开头, 则渲染为表题;
                        if (contentEls.get(i - 1).text().startsWith("表")) {
                            Element imgTitle = new Element("p");
                            imgTitle.addClass("t_title");
                            imgTitle.attr("id", "t_title_" + targetImgName.substring(0, targetImgName.lastIndexOf(".")));
                            imgTitle.html(JsoupUtil.getElementTextContainSupAndSub(currentEl.previousElementSibling()));

                            Document fieldContent = Jsoup.parse(field.getProperty());
                            fieldContent.getElementsByTag("body").get(0).children().last().remove();
                            fieldContent.append(imgTitle.toString());
                            field.setProperty(fieldContent.toString());

                        }
                        for (Element img : imgEls) {
                            String imgSrc = img.attr("src");
                            targetImgName = imgSrc.substring(imgSrc.lastIndexOf("/") + 1);
                            Element imgElement = new Element("img");
                            imgElement.attr("id", targetImgName.substring(0, targetImgName.lastIndexOf(".")));
                            imgElement.attr("src", "/ymer/action/file/showImage?filename=image/knowledge/" + knowledgeLibId + "/" + knowledge.getId() + "/" + targetImgName);
                            imgElement.attr("title", "插图");
                            imgElement.addClass("rw_img picture");
                            if (StringUtils.isNoneBlank(field.getProperty())) {
                                field.setProperty(field.getProperty() + "<p>" + imgElement.toString() + "</p>");
                            } else {
                                field.setProperty("<p>" + imgElement.toString() + "</p>");

                            }
                            File imgFile = new File(imgSrc);
                            if (imgFile.exists()) {
                                // 移动图片;
                                String dir = ApplicationContextUtil.BASE_DOWN_FORDER + "image/knowledge/" + knowledgeLibId + "/" + knowledge.getId();
                                File targetDir = new File(dir);
                                if (!targetDir.exists()) {
                                    //如果该项目名称文件夹未创建，则创建
                                    targetDir.mkdirs();
                                }
                                imgFile.renameTo(new File(dir + File.separator + targetImgName));
                            }
                        }
                        //如果下一行以"图"字开头, 则说明是图题;
                        if (contentEls.get(i + 1).text().startsWith("图")) {
                            i += 1;
                            currentEl = contentEls.get(i);
                            String substring = currentEl.text().trim().substring(currentEl.text().trim().indexOf("：") + 1);
                            Element imgTitle = new Element("p");
                            imgTitle.addClass("p_title");
                            imgTitle.attr("id", "p_title_" + targetImgName.substring(0, targetImgName.lastIndexOf(".")));
                            imgTitle.html(substring);
                            field.setProperty(field.getProperty() + imgTitle.toString());
                            continue;
                        }
                    }
                    // 不是图片;
                    else {
                        String str = "<p>" + JsoupUtil.getElementContentTextSupAndSub(currentEl) + "</p>";
                        Pattern pattern = Pattern.compile("^[0-9]+");
                        Pattern pattern1 = Pattern.compile("\\（[0-9]+\\）");
                        Pattern pattern2 = Pattern.compile("\\([0-9]+\\)");
                        if (pattern.matcher(StringUtils.deleteWhitespace(currentEl.text())).find()) {
                            if (currentEl.getElementsByTag("span").size() > 0 && currentEl.getElementsByTag("span").get(currentEl.getElementsByTag("span").size() - 1).attr("style").contains("font-weight")) {
                                str = "<p class='h1'>" + JsoupUtil.getElementTextContainSupAndSub(currentEl) + "</p>";
                            } else {
                                str = "<p>" + JsoupUtil.getElementContentTextSupAndSub(currentEl) + "</p>";
                            }
                        } else if (pattern1.matcher(StringUtils.deleteWhitespace(currentEl.text())).find() || pattern2.matcher(StringUtils.deleteWhitespace(currentEl.text())).find()) {
                            if (currentEl.getElementsByTag("span").size() > 0 && currentEl.getElementsByTag("span").get(currentEl.getElementsByTag("span").size() - 1).attr("style").contains("font-weight")) {
                                str = "<p class='h2'>" + JsoupUtil.getElementTextContainSupAndSub(currentEl) + "</p>";
                            } else {
                                str = "<p>" + JsoupUtil.getElementContentTextSupAndSub(currentEl) + "</p>";
                            }
                        }
                        if (StringUtils.isNotBlank(field.getProperty())) {
                            field.setProperty(field.getProperty() + str);
                        } else {
                            field.setProperty(str);
                        }
                    }
                }
                // 如果是输入框;
                else if (field.getKind() == KnowledgeLibField.FIELD_KIND_STRINGTEXT) {
                    if (StringUtils.isEmpty(field.getProperty())) {
                        field.setProperty(currentContent.trim());
                    } else {
                        field.setProperty(field.getProperty() + ", " + currentContent.trim());
                    }
                    fieldMap.put("name", currentContent.trim());
                    //如果是分类
                } else if (field.getKind() == KnowledgeLibField.FIELD_KIND_REFERENCE) {
                    try {
                        if (StringUtils.equals(StringUtils.deleteWhitespace(currentEl.text()), "无")) {
                            continue;
                        }
                        String tagStr = currentContent;
                        String[] split = tagStr.split("\\|");
                        String name = Arrays.stream(split).map(String::toString).collect(Collectors.joining("','", "('", "')"));
                        List<Tag> tagList = tagService.getTagName(name, field.getKindValue());
                        List<String> list = new ArrayList<>();
                        int index = 1;
                        if (tagList.size() > 0) {
                            for (int j = 0; j < split.length; j++) {
                                index = ++index;
                                if (tagList.get(j).getLevel() == index) {
                                    list.add(tagList.get(j).getId());
                                }
                            }
                        }
                        String tagId = "";
                        if (list.size() > 0) {
                            tagId = list.stream().map(String::toString).collect(Collectors.joining("\",\"", "[[\"", "\"]]"));
                            if (StringUtils.isNoneBlank(field.getProperty())) {
                                JSONArray objects = JSONArray.parseArray(field.getProperty()).fluentAddAll(JSONArray.parseArray(tagId));
                                tagId = objects.stream().map(JSON::toJSONString).collect(Collectors.joining(",", "[", "]"));
                                field.setProperty(tagId);
                            } else {
                                field.setProperty(tagId);

                            }
                        }
                        fieldMap.put("tagId", tagId);
                        fieldMap.put("tag", field.getKindValue());
                    } catch (Exception exception) {
                        exception.printStackTrace();
                        throw new RuntimeException("分类异常");
                    }
                    //多值输入框
                } else if (field.getKind() == KnowledgeLibField.FIELD_KIND_MULTI_VALUE_INPUT) {
                    String multiValue = JsoupUtil.getElementTextContainSupAndSub(currentEl).replace(" ", "");
                    String[] split = multiValue.split("\\|");
                    List<String> list = new ArrayList<>();
                    for (int j = 0; j < split.length; j++) {
                        String stringSplit = split[j];
                        list.add(stringSplit);
                    }
                    multiValue = list.stream().collect(Collectors.joining("\",\"", "[\"", "\"]"));
                    field.setProperty(multiValue);
                    //文本域
                } else if (field.getKind() == KnowledgeLibField.FIELD_KIND_TEXTAREA) {
                    if (StringUtils.isEmpty(field.getProperty())) {
                        field.setProperty(currentEl.text().trim());
                    } else {
                        field.setProperty(field.getProperty() + currentEl.text().trim());
                    }
                    //单选下拉框
                } else if (field.getKind() == KnowledgeLibField.FIELD_KIND_DROPDOWNLIST) {
                    String wherePart = " name='" + currentContent.trim() + "' and id='" + field.getKindValue() + "'";
                    List<RuleItem> ruleItem = ruleItemService.getRuleItem(wherePart);
                    if (ruleItem.size() > 0) {
                        field.setProperty(ruleItem.get(0).getId());
                    }
                    //多选下拉框
                } else if (field.getKind() == KnowledgeLibField.FIELD_KIND_DROPMULTILIST) {
                    String ruleItemValue = currentEl.text().trim().replace("；", ";");
                    String[] split = ruleItemValue.split("、");
                    List<String> list = new ArrayList<>();
                    String name = Arrays.stream(split).map(String::toString).collect(Collectors.joining("','", "('", "')"));
                    String wherePart = " name in" + name + " and rule_id='" + field.getKindValue() + "'";
                    List<RuleItem> ruleItems = ruleItemService.getRuleItem(wherePart);
                    for (RuleItem ruleItem : ruleItems) {
                        list.add(ruleItem.getId());
                    }
                    if (list.size() > 0) {
                        ruleItemValue = list.stream().collect(Collectors.joining("\",\"", "[\"", "\"]"));
                        field.setProperty(ruleItemValue);
                    }
                } else if (field.getKind() == KnowledgeLibField.FIELD_KIND_ASSOCIATE_CURRENT_KNOWLEDGE_LIB) {
                    String kowledgeName = JsoupUtil.getElementTextContainSupAndSub(currentEl).replace(" ", "");
                    String[] split = kowledgeName.split(";");
                    List<Map<String, Object>> list = new ArrayList<>();
                    String name = Arrays.stream(split).map(String::toString).collect(Collectors.joining("','", "('", "')"));
                    List<TempKnowledge> tempKnowledges = tempKnowledgeService.getBaseMapper().selectBeansByWherePart(" name in " + name + " and knowledge_lib_id='" + field.getKnowledgeLibId() + "'");
                    List<ReleasedKnowledge> releasedKnowledges = releasedKnowledgeService.getBaseMapper().selectBeansByWherePart(" name in " + name + " and knowledge_lib_id='" + field.getKnowledgeLibId() + "'");
                    if (tempKnowledges.size() > 0) {
                        for (TempKnowledge tempKnowledge : tempKnowledges) {
                            Map<String, Object> map = new HashMap<>();
                            map.put("name", tempKnowledge.getName());
                            map.put("id", tempKnowledge.getId());
                            list.add(map);
                        }
                    }
                    if (releasedKnowledges.size() > 0) {
                        for (ReleasedKnowledge releasedKnowledge : releasedKnowledges) {
                            Map<String, Object> map = new HashMap<>();
                            map.put("name", releasedKnowledge.getName());
                            map.put("id", releasedKnowledge.getId());
                            list.add(map);
                        }
                    }
                    String json = JSONArray.toJSONString(list);
                    field.setProperty(json);
                } else if (field.getKind() == KnowledgeLibField.FIELD_KIND_ASSOCIATE_OTHER_KNOWLEDGE_LIB) {

                    String kowledgeName = JsoupUtil.getElementTextContainSupAndSub(currentEl).replace(" ", "");
                    String[] split = kowledgeName.split(";");
                    List<Map<String, Object>> list = new ArrayList<>();
                    String name = Arrays.stream(split).map(String::toString).collect(Collectors.joining("','", "('", "')"));
                    List<TempKnowledge> tempKnowledges = tempKnowledgeService.getBaseMapper().selectBeansByWherePart(" name in " + name + " and knowledge_lib_id='" + field.getKnowledgeLibId() + "'");
                    List<ReleasedKnowledge> releasedKnowledges = releasedKnowledgeService.getBaseMapper().selectBeansByWherePart(" name in " + name + " and knowledge_lib_id='" + field.getKnowledgeLibId() + "'");
                    if (tempKnowledges.size() > 0) {
                        for (TempKnowledge tempKnowledge : tempKnowledges) {
                            Map<String, Object> map = new HashMap<>();
                            map.put("name", tempKnowledge.getName());
                            map.put("id", tempKnowledge.getId());
                            list.add(map);
                        }
                    }
                    if (releasedKnowledges.size() > 0) {
                        for (ReleasedKnowledge releasedKnowledge : releasedKnowledges) {
                            Map<String, Object> map = new HashMap<>();
                            map.put("name", releasedKnowledge.getName());
                            map.put("id", releasedKnowledge.getId());
                            list.add(map);
                        }
                    }
                    String json = JSONArray.toJSONString(list);
                    field.setProperty(json);
                    //图片
                } else if (field.getKind() == KnowledgeLibField.FIELD_KIND_IMG) {

                    if (contentEls.get(i).text().startsWith("图")) {
                        String substring = currentEl.text().trim().substring(currentEl.text().trim().lastIndexOf("：") + 1);
                        Map<String, String> value = JSON.parseObject(field.getProperty(), Map.class);
                        value.put("title", substring);
                        String string = JSON.toJSONString(value);
                        field.setProperty(string);
                        continue;
                    }
                    //如果下一行以"图"字开头, 则说明是图题;
                    Elements imgEls = currentEl.getElementsByTag("img");
                    if (imgEls.size() > 0) {
                        Map<String, Object> map = new HashMap<>();
                        List<String> list = new ArrayList();
                        String jsonImg = "";
                        for (Element img : imgEls) {
                            String imgSrc = img.attr("src");
                            String targetImgName = imgSrc.substring(imgSrc.lastIndexOf("/") + 1);
                            String src = "/ymer/action/file/showImage?filename=image/knowledge/" + knowledgeLibId + "/" + knowledge.getId() + "/" + targetImgName;
                            if (StringUtils.isNoneBlank(field.getProperty())) {
                                JSONObject jsonObject = JSON.parseObject(field.getProperty());
                                jsonObject.getJSONArray("paths").add(src);
                                jsonImg = JSON.toJSONString(jsonObject);
                            } else {
                                list.add(src);
                                map.put("paths", list);
                                map.put("additional", "");
                                map.put("comment", "");
                                String aClass = img.attr("class");
                                if ("".equals(aClass)) {
                                    aClass = "";
                                }
                                map.put("type", aClass);
                                map.put("classification", "");
                                map.put("title", "");
                                jsonImg = JSONObject.toJSONString(map);
                            }
                            File imgFile = new File(imgSrc);
                            if (imgFile.exists()) {
                                // 移动图片;
                                String dir = ApplicationContextUtil.BASE_DOWN_FORDER + "image/knowledge/" + knowledgeLibId + "/" + knowledge.getId();
                                File targetDir = new File(dir);
                                if (!targetDir.exists()) {
                                    //如果该项目名称文件夹未创建，则创建
                                    targetDir.mkdirs();
                                }
                                imgFile.renameTo(new File(dir + File.separator + targetImgName));
                            }
                        }
                        field.setProperty(jsonImg);
                    }
                } else if (field.getKind() == KnowledgeLibField.FIELD_KIND_VIDEO) {

                }
                if (Objects.nonNull(field)) {
                    fieldList.add(field);
                }
                //问答库
                if (StringUtils.equals(quField.getName(), "*问题")) {
                    //修改知识名称
                    tempKnowledge1.setName(StringUtils.deleteWhitespace(currentEl.text()));
                    //知识名称重复性校验;
                    List<TempKnowledge> dbTempKnowledgeList = tempKnowledgeService.lambdaQuery().eq(TempKnowledge::getKnowledgeLibId, Const.QW_LIB_ID).eq(TempKnowledge::getName, tempKnowledge1.getName()).list();
                    List<ReleasedKnowledge> dbReleasedKnowledgeList = releasedKnowledgeService.lambdaQuery().eq(ReleasedKnowledge::getKnowledgeLibId, Const.QW_LIB_ID).eq(ReleasedKnowledge::getName, tempKnowledge1.getName()).list();

                    if (CollectionUtils.isNotEmpty(dbTempKnowledgeList) || CollectionUtils.isNotEmpty(dbReleasedKnowledgeList)) {
                        if (CollectionUtils.isNotEmpty(dbTempKnowledgeList)) {
                            List<String> tempKnowledgeIds = dbTempKnowledgeList.stream().map(TempKnowledge::getId).collect(Collectors.toList());
                            tempKnowledgeFieldService.remove(Wrappers.lambdaQuery(TempKnowledgeField.class).in(TempKnowledgeField::getKnowledgeId, tempKnowledgeIds));
                            taskItemService.remove(Wrappers.lambdaQuery(TaskItem.class).in(TaskItem::getKnowledgeId, tempKnowledgeIds));
                            tempKnowledgeService.removeByIds(tempKnowledgeIds);
                        } else {
                            if (tempKnowledge1.getName().equals("*问题")) {
                                tempKnowledgeService.removeById(tempKnowledge1.getId());
                                continue;
                            }
                            tempKnowledgeService.removeById(tempKnowledge1.getId());
                            continue;
                        }
                    }
                    tempKnowledgeService.saveOrUpdate(tempKnowledge1);
                    TempKnowledgeField tempKnowledgeField = new TempKnowledgeField();
                    tempKnowledgeField.setName("名称");
                    tempKnowledgeField.setKind(KnowledgeLibField.FIELD_KIND_STRINGTEXT);
                    tempKnowledgeField.setProperty(StringUtils.deleteWhitespace(currentEl.text()));
                    tempKnowledgeField.setKnowledgeId(tempKnowledge1.getId());
                    tempKnowledgeField.setIndex(0);
                    tempKnowledgeField.setKnowledgeLibFieldId(knowledgeLibField.get(0).getId());
                    tempKnowledgeFieldService.saveOrUpdate(tempKnowledgeField);

                    TempKnowledgeField department = new TempKnowledgeField();
                    department.setName("科室");
                    department.setProperty(fieldMap.get("tagId"));
                    department.setKindValue(fieldMap.get("tag"));
                    department.setKind(KnowledgeLibField.FIELD_KIND_REFERENCE);
                    department.setKnowledgeId(tempKnowledge1.getId());
                    department.setKnowledgeLibFieldId(knowledgeLibField.get(1).getId());
                    department.setIndex(1);
                    tempKnowledgeFieldService.saveOrUpdate(department);

                    TempKnowledgeField disease = new TempKnowledgeField();
                    disease.setName("关联疾病");
                    //disease.setProperty(fieldMap.get("name"));
                    if(fieldMap.get("name")==null){
                        throw new RuntimeException("知识名称不能为空");
                    }
                    disease.setProperty(JSONArray.toJSONString(fieldMap.get("name").split(",")));
                    disease.setKind(KnowledgeLibField.FIELD_KIND_MULTI_VALUE_INPUT);
                    disease.setKnowledgeId(tempKnowledge1.getId());
                    disease.setIndex(2);
                    disease.setKnowledgeLibFieldId(knowledgeLibField.get(2).getId());
                    tempKnowledgeFieldService.saveOrUpdate(disease);

                    TaskItem taskItem = new TaskItem();
                    taskItem.setName(tempKnowledge1.getName());
                    taskItem.setKnowledgeId(tempKnowledge1.getId());
                    taskItem.setKnowledgeLibId(Const.QW_LIB_ID);
                    taskItem.setStatus(TaskItem.STATUS_NOT_COMMIT);
                    taskItem.setDeleted(TaskItem.NO_DELETED);
                    taskItem.setTaskId(questionAnswerTaskId);
                    taskItem.setRelationDisease(fieldMap.get("name"));
                    taskItemService.save(taskItem);
                }
                if (StringUtils.equals(quField.getName(), "*答案")) {
                    List<TempKnowledge> list = tempKnowledgeService.lambdaQuery().eq(TempKnowledge::getId, tempKnowledge1.getId()).list();
                    if (CollectionUtils.isNotEmpty(list)) {
                        String str = "<p>" + JsoupUtil.getElementTextContainSupAndSub(currentEl) + "</p>";
                        Pattern pattern = Pattern.compile("^[0-9]+");
                        Pattern pattern1 = Pattern.compile("\\（[0-9]+\\）");
                        Pattern pattern2 = Pattern.compile("\\([0-9]+\\)");

                        if (pattern.matcher(StringUtils.deleteWhitespace(currentEl.text())).find()) {
                            if (currentEl.getElementsByTag("span").size() > 0 && currentEl.getElementsByTag("span").get(currentEl.getElementsByTag("span").size() - 1).attr("style").contains("font-weight")) {
                                str = "<p class='h1'>" + JsoupUtil.getElementTextContainSupAndSub(currentEl) + "</p>";
                            } else {
                                str = "<p>" + JsoupUtil.getElementContentTextSupAndSub(currentEl) + "</p>";
                            }
                        } else if (pattern1.matcher(StringUtils.deleteWhitespace(currentEl.text())).find() || pattern2.matcher(StringUtils.deleteWhitespace(currentEl.text())).find()) {
                            if (currentEl.getElementsByTag("span").size() > 0 && currentEl.getElementsByTag("span").get(currentEl.getElementsByTag("span").size() - 1).attr("style").contains("font-weight")) {
                                str = "<p class='h2'>" + JsoupUtil.getElementTextContainSupAndSub(currentEl) + "</p>";
                            } else {
                                str = "<p>" + JsoupUtil.getElementContentTextSupAndSub(currentEl) + "</p>";
                            }
                        }
                        tempField.setName("答案");
                        tempField.setKnowledgeLibFieldId(knowledgeLibField.get(3).getId());
                        tempField.setKind(KnowledgeLibField.FIELD_KIND_RICHEDITOR);
                        if (StringUtils.isNotBlank(tempField.getProperty())) {
                            tempField.setProperty(tempField.getProperty() + str);
                        } else {
                            tempField.setProperty(str);
                        }
                        tempField.setKnowledgeId(tempKnowledge1.getId());
                        tempField.setIndex(3);
                        tempKnowledgeFieldService.saveOrUpdate(tempField);
                        int num = countTheNumberOfWords(tempKnowledge1.getId());
                        //新增问答库活动详情
                        taskItemService.update(Wrappers.lambdaUpdate(TaskItem.class)
                                .set(TaskItem::getWordsCount, num)
                                .eq(TaskItem::getKnowledgeId, tempKnowledge1.getId()));

                    }
                }
            }
        }

        knowledge.setKnowledgeFieldList(fieldList);
        return knowledge;
    }

    public void resetKnowledgeFieldList(Knowledge knowledge) {
        Knowledge dbKnowledge = getKnowledgeAndFieldById(knowledge.getId());
        if (Objects.nonNull(dbKnowledge)) {
            knowledge.setKnowledgeFieldList(dbKnowledge.getKnowledgeFieldList());
        } else {
            createAndSetKnowledgeFieldList(knowledge);
        }
    }

    public KnowledgeField selectByKnowledgeId(String knowledgeId) {
        String filePath = StringUtils.substringBeforeLast(ApplicationContextUtil.getProperty("static-file.path"), "/");
        KnowledgeField knowledgeField = tempKnowledgeFieldService.lambdaQuery().eq(TempKnowledgeField::getKnowledgeId, knowledgeId)
                .eq(TempKnowledgeField::getKnowledgeLibFieldId, Const.NEW_MEDIA_LIB_MAIN_BODY_ID).one();
        if (Objects.isNull(knowledgeField)) {
            knowledgeField = releasedKnowledgeFieldService.lambdaQuery().eq(ReleasedKnowledgeField::getKnowledgeId, knowledgeId)
                    .eq(ReleasedKnowledgeField::getKnowledgeLibFieldId, Const.NEW_MEDIA_LIB_MAIN_BODY_ID).one();
        }
        // 因图片需要在135网站上显示,所有图片拼接访问路径
        Element body = Jsoup.parse(Parser.unescapeEntities(StringUtils.defaultIfBlank(knowledgeField.getPropertyEditor135(), knowledgeField.getProperty()), false)).body();
        body.getElementsByTag("img").forEach(imgItem -> {
            // 取得图片的src属性
            String src = imgItem.attr("src");
            if (src.startsWith(filePath)) {
                return;
            }
            imgItem.attr("src", filePath + imgItem.attr("src"));
        });
        body.getElementsByTag("video").forEach(videoItem -> {
            // 取得视频的src属性
            String src = videoItem.attr("src");
            if (src.startsWith(filePath)) {
                return;
            }
            videoItem.attr("src", filePath + src);
            videoItem.attr("poster", filePath + videoItem.attr("poster"));
        });
        knowledgeField.setPropertyEditor135(Parser.unescapeEntities(body.html(), false));
        return knowledgeField;
    }

    public void updateFieldById(TempKnowledgeField tempKnowledgeField) {
        //处理所有图片
        String newImgSrc = ApplicationContextUtil.getProperty("static-file.path") + "ymer/action/file/showEditor135Image?filename=image/knowledge/"
                + Const.NEW_MEDIA_LIB_ID + "/" +
                tempKnowledgeField.getKnowledgeId() + "/";
        Element body = Jsoup.parse(tempKnowledgeField.getPropertyEditor135().replaceAll("&quot;", "")).body();
        body.getElementsByTag("img").forEach(imgItem -> {
            // 取得图片的src属性
            String src = imgItem.attr("src");
            // 如果是本平台图片,直接跳过
            if (src.startsWith(ApplicationContextUtil.getProperty("static-file.path"))) {
                return;
            }
            imgItem.attr("src", downloadImg(src, tempKnowledgeField, newImgSrc));
        });
        // 因style样式中可能含有图片,处理
        // 因存在style样式里含有背景图片,找到所有的style样式,http链接前加上
        body.getAllElements().forEach(element -> {
            String style = element.attr("style");
            if (StringUtils.isBlank(style)) {
                return;
            }
            element.attr("style", filterSpecialStr(style, tempKnowledgeField, newImgSrc));
        });
        body.getElementsByTag("video").forEach(videoItem -> {
            // 取得图片的src属性
            String src = videoItem.attr("src");
            // 如果是本平台图片,去掉http://ip:port
            if (!src.startsWith(ApplicationContextUtil.getProperty("static-file.path"))) {
                throw new RuntimeException("未知的video标签:" + src);
            }
        });
        LambdaUpdateWrapper<TempKnowledgeField> lambdaUpdateWrapper = new LambdaUpdateWrapper<>();
        lambdaUpdateWrapper.set(TempKnowledgeField::getPropertyEditor135, Parser.unescapeEntities(body.html(), false))
                .eq(TempKnowledgeField::getId, tempKnowledgeField.getId());
        tempKnowledgeFieldService.getBaseMapper().update(null, lambdaUpdateWrapper);
        LambdaUpdateWrapper<TempKnowledge> tempKnowledgeLambdaUpdateWrapper = new LambdaUpdateWrapper<>();
        tempKnowledgeLambdaUpdateWrapper.set(TempKnowledge::getIsCompose, 1)
                .eq(TempKnowledge::getId, tempKnowledgeField.getKnowledgeId());
        tempKnowledgeService.getBaseMapper().update(null, tempKnowledgeLambdaUpdateWrapper);
    }

    private String filterSpecialStr(String style, TempKnowledgeField tempKnowledgeField, String newImgSrc) {
        //编译正则字符串
        Pattern p = Pattern.compile(Const.REGEX_URL);
        //利用正则去匹配
        Matcher matcher = p.matcher(style);
        //如果找到了我们正则里要的东西
        while (matcher.find() && !(matcher.group().startsWith(ApplicationContextUtil.getProperty("static-file.path")))) {
            style = style.replace(matcher.group(), downloadImg(matcher.group(), tempKnowledgeField, newImgSrc));
        }
        return style;
    }

    private String downloadImg(String src, TempKnowledgeField tempKnowledgeField, String newImgSrc) {
        // 下载图片到本地, 部分地址无法根据url取得文件类型
        BufferedInputStream bis = null;
        HttpURLConnection urlconnection = null;
        String newImgName = IdWorker.getIdStr();
        String suffix = "";
        try {
            URL url = new URL(src);
            // 需要判断下是否包含后缀名,如果包含后缀名,该方法不适用
            if (StringUtils.substringAfterLast(src, "/").contains(".")) {
                suffix = StringUtils.substringAfterLast(src, ".");
            } else {
                urlconnection = (HttpURLConnection) url.openConnection();
                urlconnection.connect();
                bis = new BufferedInputStream(urlconnection.getInputStream());
                suffix = HttpURLConnection.guessContentTypeFromStream(bis);
                suffix = suffix.substring(suffix.lastIndexOf("/") + 1);
            }
            FileUtils.copyURLToFile(url, new File(ApplicationContextUtil.BASE_DOWN_FORDER + "image/knowledge/" +
                    Const.NEW_MEDIA_LIB_ID + "/" + tempKnowledgeField.getKnowledgeId() + "/" + newImgName + "." + suffix));
        } catch (Exception e) {
            throw new RuntimeException("图片下载失败:" + src);
        } finally {
            try {
                if (Objects.nonNull(bis)) {
                    bis.close();
                }
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
        return newImgSrc + newImgName + "." + suffix;
    }
}
